﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Streaming_Service.Web {
    using System.IO;

    using Streaming_Service.Enum;
    using Streaming_Service.Media;
    using Streaming_Service.SQL_Ting;
    using Streaming_Service.Web.Helpers;

    public partial class moviedownload : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {
            Response.Clear();

            var id = RequestFunc.GetQueryStringInt(Request, "vid");
            var hd = RequestFunc.GetQueryStringBool(Request, "hd");
            var stream = RequestFunc.GetQueryStringBool(Request, "str");

            if (id > 0) {
                if (MediaFunc.MovieFolderExists(id, hd)) {
                    var filepath = MediaFunc.GetMoviePath(id, hd);
                    if (!string.IsNullOrEmpty(filepath) && File.Exists(filepath)) {
                        var sh = DBHandler.GetHandler();
                        sh.Connect();
                        var mEntry = MovieQueries.GetMovie(id, sh);
                        sh.Close();

                        var fileInfo = new FileInfo(filepath);
                        var filename = mEntry.Title + " (" + mEntry.Year + ")" + (hd ? " [HD]" : "") + fileInfo.Extension;
                        if(!stream) Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

                        Response.ContentType = MediaFunc.GetContentType(filepath);
                        Response.TransmitFile(filepath);
                    } else {
                        Response.Write("Movie not available in specified definition.<!-- " + filepath + " -->");
                    }
                } else {
                    this.Response.Write(
                        MediaFunc.MovieFolderExists(id, !hd)
                        ? "Movie only available in " + (hd ? "SD" : "HD") + "."
                            : "Movie not available.");
                }
            } else {
                Response.Write("No ID specified.");
            }
        }
    }
}